<template>
  <EcDialog v-model="dialogVisible" :auto-height="true" class="form-dialog">
    <!-- 标题 -->
    <template #title>
      <div class="dialog-title">
        <SvgIcon :icon="dialogIconMap[dialogMode]"/>
        <span>{{ dialogModeMap[dialogMode] + ' - ' + dialogTitle }}</span>
      </div>
    </template>

    <!-- 表单数据 -->
    <el-form ref="formRef"
             v-loading="dataLoading"
             :disabled="readonly"
             :model="formData"
             :rules="formRules"
             label-width="110px">

      <el-form-item label="名称：" prop="name">
        <el-input v-model="formData.name" :readonly="readonly" placeholder="请输入连锁店名称"/>
      </el-form-item>

      <el-form-item label="公排状态：" prop="public_status">
        <DictTag v-if="readonly" v-model="formData.public_status" :circle="false" dict-type="sys_open"/>
        <DictSelect v-else v-model="formData.public_status" :disable-key="2" :radio-group="true" dict-type="sys_open" @change="handleChangePublicStatus"/>
      </el-form-item>

      <template v-if="formData.public_status == 1">
        <el-form-item label="公排类型：" prop="public_queue_type" @change="handleChangePublicQueueType">
          <DictTag v-if="readonly" v-model="formData.public_queue_type" :circle="false" dict-type="public_queue_type"/>
          <DictSelect v-else v-model="formData.public_queue_type" :radio-group="true" dict-type="public_queue_type"/>
        </el-form-item>

        <el-form-item v-if="formData.public_queue_type == 10" label="门店联盟：" prop="public_queue_code">
          <el-select v-model="formData.public_queue_code" :disabled="readonly" placeholder="请选择联盟">
            <el-option v-for="item in storeAllianceList" :key="item.code" :label="item.name" :value="item.code"/>
          </el-select>
        </el-form-item>
      </template>

      <el-form-item label="补贴配置：" prop="subsidy_config_id">
        <el-select v-model="formData.subsidy_config_id" :disabled="readonly" placeholder="请选择补贴配置" value="" @change="handleChangeSubsidyConfig">
          <el-option v-for="item in subsidyConfigList" :key="item.id" :label="item.name" :value="item.id">
            <span style="float: left">{{ item.name }}</span>
            <span v-if="item.mode" style="float: right;color: var(--el-text-color-secondary);font-size: 13px;">{{ item.mode == 2 ? '2.0' : item.mode == 1 ? '1.0' : '' }}</span>
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="补贴比例：" prop="subsidy_ratio">
        <el-input-number v-model="formData.subsidy_ratio" :max="2" :min="0" :precision="3" :step="0.1" controls-position="right"/>
        <span v-if="formData.subsidy_ratio != undefined" class="tip">{{ toPercent(formData.subsidy_ratio) }}</span>
      </el-form-item>

      <el-form-item label="让利比例：" prop="rebate_ratio">
        <el-input-number v-model="formData.rebate_ratio" :max="0.9" :min="0" :precision="3" :step="0.01" controls-position="right"/>
        <span v-if="formData.rebate_ratio != undefined" class="tip">{{ toPercent(formData.rebate_ratio) }}</span>
      </el-form-item>

      <el-form-item label="推广奖金：" prop="promotion_ratio">
        <el-input-number v-model="formData.promotion_ratio" :max="0.3" :min="0" :precision="3" :step="0.01" controls-position="right"/>
        <span v-if="formData.promotion_ratio != undefined" class="tip">{{ toPercent(formData.promotion_ratio) }}</span>
      </el-form-item>

      <el-form-item label="联盟服务费：" prop="service_fee_ratio">
        <el-input-number v-model="formData.service_fee_ratio" :max="0.3" :min="0" :precision="3" :step="0.01" controls-position="right"/>
        <span v-if="formData.service_fee_ratio != undefined" class="tip">{{ toPercent(formData.service_fee_ratio) }}</span>
      </el-form-item>

    </el-form>

    <!-- 底部操作区域 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button :loading="dataLoading" @click="dialogVisible = false">取 消</el-button>
        <el-button v-if="!readonly" v-permission="['store:category:create', 'store:category:update']" :loading="dataLoading" type="primary" @click="onSubmitForm()">确 定</el-button>
      </span>
    </template>
  </EcDialog>
</template>

<script lang="ts" setup>
import { computed, reactive, ref } from 'vue';
import { ElLoading, ElMessage, ElNotification, FormInstance, FormRules } from 'element-plus';
import { EcDialog } from '@/components/dialog';
import { SvgIcon } from '@/components/icon';
import useDialog from '@/hooks/use-dialog.ts';
import { StoreAlliance, StoreChain, storeChainInfo, storeChainSaveOrUpdate, storeConfig } from '@/api/api-store.ts';
import { toPercent } from '@/utils';
import { DictTag } from '@/components/dict-tag';
import { DictSelect } from '@/components/dict-select';
import { SubsidyConfig } from '@/api/api-subsidy.ts';

defineOptions({name: 'store-chain-form'})

const formRef = ref<FormInstance>();
const formLoading = ref(false); // 表单是否加载中
const {dialogVisible, dialogTitle, dialogMode, dialogModeMap, dialogIconMap} = useDialog(false);

/** 默认表单数据 */
const defaultForm: StoreChain = <StoreChain>{
  id: 0, public_status: 1, public_queue_type: 1, subsidy_config_id: 0, rebate_ratio: 0.00, subsidy_ratio: 0.00, promotion_ratio: 0.00, service_fee_ratio: 0.00
};

// 表单数据
const formData = ref({...defaultForm});
const ratioType = ref();

// 表单验证规则
const formRules = reactive<FormRules>({
  name: [{required: true, message: '连锁店名称不能为空', trigger: 'blur'}],
  public_status: [{required: true, message: '公排状态不能为空', trigger: 'blur'}],
  public_queue_type: [{required: true, message: '公排类型不能为空', trigger: 'blur'}],
  subsidy_config_id: [{required: true, message: '请选择补贴配置', trigger: 'blur'}],
  subsidy_ratio: [{required: true, message: '补贴比例不能为空', trigger: 'blur'}],
  rebate_ratio: [{required: true, message: '让利比例不能为空', trigger: 'blur'}],
  promotion_ratio: [{required: true, message: '推广奖金比例不能为空', trigger: 'blur'}],
  service_fee_ratio: [{required: true, message: '联盟服务费比例不能为空', trigger: 'blur'}],
});

/** 判断数据是否处于加载中 */
const dataLoading = computed(() => {
  return formLoading.value;
})

/** 是否只读 */
const readonly = computed(() => {
  return dialogMode.value == 0;
});

/** 是否新增 */
const isCreate = computed(() => {
  return dialogMode.value == 1 || formData.value.id <= 0;
});

/** 打开弹窗 */
const open = async (mode: number, id?: number) => {
  dialogMode.value = mode;
  dialogTitle.value = '连锁店管理';
  dialogVisible.value = true;
  // 重置表单
  handleFormReset();
  // 加载门店配置
  await initStoreConfig();

  // 加载数据
  if (id) {
    formLoading.value = true
    try {
      // 加载用户数据
      const {data} = await storeChainInfo(id)
      formData.value = data;
      handleChangePublicQueueType();
    } finally {
      formLoading.value = false
    }
  }
}
// 提供 open 方法，用于打开弹窗
defineExpose({open});

/** 表单提交 */
const emit = defineEmits(['refresh']);
const onSubmitForm = async () => {
  await formRef.value?.validate((valid, fields) => {
    if (!valid) {
      ElMessage({type: 'error', message: '请检查是否有必填项未完善',});
      return
    }
    const loading = ElLoading.service({
      lock: true,
      text: '正在提交中...',
      background: 'rgba(0, 0, 0, 0.2)'
    })
    // 提交数据
    storeChainSaveOrUpdate(formData.value, isCreate.value).then(response => {
      // 提示信息
      ElNotification({title: '成功', message: '操作完成', type: 'success', duration: 2000})
      // 发送操作成功的事件
      emit('refresh')
      // 隐藏窗口
      dialogVisible.value = false
    }).finally(() => loading.close())

  });
};

/** 重置表单 */
const handleFormReset = () => {
  ratioType.value = undefined;
  // 重置表单数据
  formData.value = {...defaultForm};
  // 重置界面表单数据
  formRef.value?.resetFields();
};

/** 加载门店配置 */
const subsidyConfigList = ref<SubsidyConfig[]>([]);
const storeAllianceList = ref<StoreAlliance[]>([]);
const initStoreConfig = async () => {
  subsidyConfigList.value = [];
  storeAllianceList.value = [];
  try {
    const {data} = await storeConfig();
    subsidyConfigList.value = data.subsidy || []
    storeAllianceList.value = data.alliance || []
  } finally {

  }
};

/** 公排类型被改变 */
const handleChangePublicQueueType = () => {
  if (formData.value.public_queue_type != 10 || formData.value.public_queue_code == 0) {
    formData.value.public_queue_code = undefined;
  }
};

/** 门店补贴配置选择改变 */
const handleChangeSubsidyConfig = (val: any) => {
  let item = subsidyConfigList.value.find(item => item.id == val);
  if (item) {
    formData.value.rebate_ratio = item.rebate_ratio;
    formData.value.subsidy_ratio = item.subsidy_ratio;
    formData.value.promotion_ratio = item.promotion_ratio;
    formData.value.service_fee_ratio = item.service_fee_ratio;
  } else {
    formData.value.rebate_ratio = 0.0;
    formData.value.subsidy_ratio = 0.0;
    formData.value.promotion_ratio = 0.0;
    formData.value.service_fee_ratio = 0.0;
  }
};

/** 公排状态被改变 */
const handleChangePublicStatus = () => {

};

</script>

<style lang="scss" scoped>
.form-dialog {
  .el-select {
    max-width: 16rem;
  }

  .el-input-number {
    max-width: 10rem;
  }
}
</style>
